import registerGlobalComponent from '@/plugins/registerGlobalComponent'
import NProgress from 'nprogress'
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import directives from './directives/index'
import router from './router/index'
import useMenuTreeStore from './store/menuTree'
import 'nprogress/nprogress.css'
import 'ant-design-vue/dist/reset.css'
import 'virtual:uno.css'
import './assets/style/index.less'

const app = createApp(App)

directives.install(app)
registerGlobalComponent(app)

app.use(router)
app.use(createPinia())

app.config.errorHandler = (err) => {
  console.error(err)
}
app.mount('#app')

router.beforeEach((to, from, next) => {
  NProgress.start()
  const token = sessionStorage.getItem('token')
  if (!token && to.path !== '/login') {
    next({ path: '/login' })
    return false
  }
  if (!router.hasRoute(to.name)) {
    const { generateRoutes, routerDone } = useMenuTreeStore()
    if (routerDone) {
      next({ path: '/' })
      return false
    }
    else {
      generateRoutes().then(() => {
        next({ path: to.path })
      })
    }
  }
  else {
    next()
  }
})

router.afterEach((to, from, failure) => {
  NProgress.done()
})

router.onError((err) => {
  console.error(err)
})
